import os
import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class WishlistCategory(db.Model):
	title = db.StringProperty(required=True)
	category = db.SelfReferenceProperty()

class Wishlist(db.Model):
	author = db.UserProperty(required=True)
	title = db.StringProperty(required=True)
	category = db.ReferenceProperty(required=True)

class WishlistItem(db.Model):
	wishlist = db.ReferenceProperty(Wishlist)
	name = db.StringProperty(required=True)
	page = db.StringProperty(required=True)
	pic_url = db.StringProperty()

class Greeting(db.Model):
	author = db.UserProperty()
	content = db.StringProperty(multiline=True)
	date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
		category = self.request.get('category')
		if not category:
			category = WishlistCategory(title="All Wishlists", category=None)

		categories = WishlistCategory.all().filter('category =', category.category)

		logged_in_user = users.get_current_user()

		if logged_in_user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout ' + users.get_current_user().nickname()
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'

		template_values = {
				'logged_in_user' : logged_in_user,
				'category' : category,
				'categories' : categories,
				'url' : url,
				'url_linktext': url_linktext,
				}

		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication( [ ( '/', MainPage) ,
                                 	  ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
